//
//  twoViewController.swift
//  test
//
//  Created by admin on 2016/12/12.
//  Copyright © 2016年 Zhongshan Camry Electronic Company Limited. All rights reserved.
//

import UIKit

class twoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        lock()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    
    //MARK: - lock
    dynamic func lock() {
        let lock = NSLock()
        let group = DispatchGroup()
        let queue1 = DispatchQueue(label: "queue1")
        queue1.async(group: group, qos: .default, flags: .noQoS) {
            lock.lock(before: Date())
            print("需要线程同步的操作1 开始")
            sleep(3)
            print("需要线程同步的操作1 结束")
            lock.unlock()
        }
        let queue2 = DispatchQueue(label: "queue2")
        queue2.async(group: group, qos: .default, flags: .noQoS) {
            sleep(1)
            if lock.try() {
                print("需要线程同步的操作2")
                lock.unlock()
            } else {
                print("线程被锁死")
            }
            if lock.lock(before: Date(timeIntervalSinceNow: 3.0)) {
                print("线程没有被锁死")
            } else{
                print("超时，线程被锁死")
            }
        }
        
    }
    //MARK: - @synchronized
    func lock1() {
        let objc = NSObject()
        let group = DispatchGroup()
        let queue1 = DispatchQueue(label: "queue1")
        queue1.async(group: group, qos: .default, flags: .noQoS) {
            self.synchronized(lock: objc, f: { 
                print("需要线程同步的操作1 开始")
                sleep(3)
                print("需要线程同步的操作1 结束")
            })
        }
        let queue2 = DispatchQueue(label: "queue2")
        queue2.async(group: group, qos: .default, flags: .noQoS) {
            sleep(1)
            //如果synchronized传入的是self，线程2则不会被阻塞，只有两个标示相同时才能满足线程的互斥
            //由于synchronized会隐式的添加一个异常处理来保护现有的线程，这在swift中是不允许的
            self.synchronized(lock: self, f: { //这种情况不会有线程锁
                print("需要线程同步的操作2")
            })
        }
        
    }
    
    // MARK: - 线程🔒
    /// - 由于swift不支持synchronized的方法，故需要自定义
    /// - Parameters:
    ///   - lock: AnyObject
    ///   - f: 传入的必报
    func synchronized(lock:AnyObject, f:()->()) {
        objc_sync_enter(lock)
        f()
        objc_sync_exit(lock)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
